﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Windows.Forms;
using TigerCapture.Utils;

namespace TigerCapture.Presentation
{
    public partial class Uploader : Form
    {
        private const string LoginUrl = "http://39.107.245.16:10011/admin/login/login";
        private const string UploadUrl = "http://39.107.245.16:10031/os/storage/create";

        //private string _loginUrlFormatter;

        private string _token;

        public Uploader()
        {
            InitializeComponent();

            btnUpload.Enabled = false;

            //_loginUrlFormatter = string.Format("{0}?username={{0}}&password={{1}}", LoginUrl);
        }

        private void Log(string message)
        {
            tbxMessage.AppendText(string.Format("{0}{1}", message, Environment.NewLine));
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(tbxUserName.Text))
            {
                Log("用户名不可为空");

                return;
            }

            if (string.IsNullOrWhiteSpace(tbxPassword.Text))
            {
                Log("密码不可为空");

                return;
            }

            //var requestUrl = string.Format(_loginUrlFormatter, tbxUserName.Text.Trim(), tbxPassword.Text);

            var parames = new NameValueCollection
            {
                { "username", tbxUserName.Text.Trim() },
                { "password", tbxPassword.Text }
            };

            try
            {
                //var result = HttpHelper.RequestResult(requestUrl);

                var result = HttpHelper.PostData(LoginUrl, parames);

                var jo = JObject.Parse(result);

                var code = jo.GetValue("errno").Value<int>();
                var message = jo.GetValue("errmsg").Value<string>();

                if (code == 0)
                {
                    var jt = jo.GetValue("data");

                    _token = jt.Value<string>("X-Token");

                    btnUpload.Enabled = true;

                    Log("登录成功，请点击【上传】按钮开始上传视频。");
                }
                else
                {
                    Log(string.Format("登录失败：{0}-{1}", code, message));
                }
            }
            catch (Exception ex)
            {
                Log(string.Format("登录时发生错误：{0}", ex.Message));
            }
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            var files = Directory.GetFiles(Ribbon.OutDirectory);

            if (files.Length > 0)
            {
                foreach (var file in files)
                {
                    try
                    {
                        string responseInfo;

                        Log(string.Format("正在上传文件：{0}", file));

                        HttpHelper.UploadFile(file, UploadUrl, "file",
                            Path.GetFileName(file),
                            new NameValueCollection { { "X-Token", _token } },
                            p => { },
                            out responseInfo);

                        var jo = JObject.Parse(responseInfo);

                        var code = jo.GetValue("errno").Value<int>();
                        var message = jo.GetValue("errmsg").Value<string>();

                        if (code == 0)
                        {
                            Log("上传文件成功");

                            File.Delete(file);
                        }
                        else
                        {
                            Log(string.Format("上传文件失败：{0}-{1}", code, message));
                        }
                    }
                    catch (Exception ex)
                    {
                        Log(string.Format("上传文件时发生错误：{0}", ex.Message));
                    }
                }
            }
            else
            {
                Log("没有文件上传");
            }
        }
    }
}
